package com.zhengyisky.controller;

import com.zhengyisky.utils.Result;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @DeleteMapping("/delete")
    public Result delete(){
        return null;
    }


    @PostMapping("/add")
    public Result add(){
        return null;
    }


    @GetMapping("/list")
    public Result list(Integer page, Integer size, String name,
                       String orderCode, Integer userId, Date startDate, Date endDate) throws IOException {

        //1、设置库名和表名
        SearchRequest searchRequest = new SearchRequest("month2112a");
        searchRequest.types("purchase");

        //2、创建searchSourceBuilder对象,装入到searchRequest
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //设置分页条件
        searchSourceBuilder.from((page-1)*size);
        searchSourceBuilder.size(size);

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name");
        highlightBuilder.preTags("<bw>");
        highlightBuilder.postTags("</bw>");
        searchSourceBuilder.highlighter(highlightBuilder);


        //3、创建一个bool查询，装入SearchSourceBuilder
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        if(name != null && !"".equals(name)){
            MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("name", name);
            boolQueryBuilder.must(matchQuery);
        }

        if(orderCode != null && !"".equals(orderCode)){
            TermQueryBuilder termQuery = QueryBuilders.termQuery("order_code", orderCode);
            boolQueryBuilder.must(termQuery);
        }

        if(userId != null){
            TermQueryBuilder termQuery = QueryBuilders.termQuery("user_id", userId);
            boolQueryBuilder.must(termQuery);
        }

        if(startDate != null){
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("sign_date").gte(startDate);
            boolQueryBuilder.must(rangeQueryBuilder);
        }

        if(endDate != null){
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("sign_date").lte(endDate);
            boolQueryBuilder.must(rangeQueryBuilder);
        }


        searchSourceBuilder.query(boolQueryBuilder);

        searchRequest.source(searchSourceBuilder);

        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        SearchHits hits = response.getHits();
        long total = hits.getTotalHits().value;


        SearchHit[] hits1 = hits.getHits();
        List list = new ArrayList<>();
        for (SearchHit hit : hits1) {

            Map<String, Object> data = hit.getSourceAsMap();

            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if(highlightFields.size()>0){
                HighlightField highlightField = highlightFields.get("name");
                String hlName = highlightField.getFragments()[0].toString();
                data.put("hlName", hlName);
            }

            list.add(data);
        }


        Map result = new HashMap<>();
        result.put("total", total);
        result.put("list", list);

        return Result.success(result);
    }
}
